package com.googlecode.tracey.messageserver;

import com.googlecode.funclate.Model;
import com.googlecode.funclate.stringtemplate.EnhancedStringTemplateGroup;
import com.googlecode.totallylazy.Xml;
import com.googlecode.utterlyidle.MatchedResource;
import com.googlecode.utterlyidle.Renderer;
import com.googlecode.utterlyidle.sitemesh.TemplateName;

import static com.googlecode.totallylazy.Predicates.instanceOf;
import static com.googlecode.totallylazy.URLs.packageUrl;

public class ModelRenderer implements Renderer<Model> {
    private final TemplateName templateName;
    private MatchedResource resource;
    public static final String TEMPLATE_NAME = "TEMPLATE_NAME";

    public ModelRenderer(TemplateName templateName, MatchedResource matchedResource) {
        this.templateName = templateName;
        resource = matchedResource;
    }

    public String render(Model model) throws Exception {
        final EnhancedStringTemplateGroup templateGroup = new EnhancedStringTemplateGroup(packageUrl(resource.forClass()));
        templateGroup.registerRenderer(instanceOf(String.class), Xml.escape());

        return templateGroup.getInstanceOf(templateName(model), model.toMap()).toString();
    }

    private String templateName(Model model) {
        return model.contains(TEMPLATE_NAME) ? model.get(TEMPLATE_NAME, String.class) : templateName.value();
    }
}
